﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db;
using System.Threading;
using System.Reflection;
using System.ComponentModel;

namespace yq.Language
{
    /// <summary>
    /// 多语言化
    /// </summary>
    public class Change
    {
        /// <summary>
        /// 语言缓存
        /// </summary>
        static Dictionary<string, string> Cache = new Dictionary<string, string>();


        /// <summary>
        /// 初始化到内存
        /// </summary>
        static Change()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            List<string> list = yq.Language.ConfigEnum.EN.GetList();
            foreach (string key in list)
            {
                ReadSQL(key, dic);
            }
            Cache = dic;
        }


        /// <summary>
        /// 翻译
        /// </summary>
        /// <param name="key"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static string Translate(string key, ConfigEnum lang = ConfigEnum.Zh_CN)
        {
            string tableName = lang.ExtName().ToString();

            //检测是否需要翻译
            if (Config.IsEnable&& lang != Config.Default)
            {
                string keyExcision = key + Config.Excision + tableName;

                //查找匹配
                if (Cache.ContainsKey(keyExcision))
                {
                    return Cache[keyExcision];

                }else if (Config.Write)
                {
                    //如果没有匹配并且开启写模式
                    Thread td = new Thread(() => { WriteSQL(key); });
                    td.Start();
                }

                return key;
            }
            else
            {

                return key;
            }
        }

        #region 数据库操作
        
        /// <summary>
        /// 写入错误数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="title"></param>
        /// <param name="other"></param>
        /// <param name="cn"></param>
        /// <param name="logLevel"></param>
        /// <returns></returns>
        private static void WriteSQL(string key)
        {
            try
            {
                List<string> list =yq.Language.ConfigEnum.EN.GetList();
                foreach (string table in list)
                {
                    var cn = new Db.DbHelper(Config.DbConnectionString, Config.DbProviderName);
                    string sql = "insert into " + table + " values(@id,null)";
                    var comm = cn.GetSqlStringCommond(sql);
                    cn.AddInParameter(comm, "@id", System.Data.DbType.String, key);
                    cn.ExecuteNonQuery(comm);
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 读取数据库
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="key"></param>
        private static void ReadSQL(string tableName, Dictionary<string, string> dic)
        {
            try
            {
                //是否存在表
                if (CreateTableExist(tableName) == false)
                {
                    //如果没有创建表
                    CreateTable(tableName);
                }

                var cn = new Db.DbHelper(Config.DbConnectionString, Config.DbProviderName);
                string sql = "select * from " + tableName + "";
                var comm = cn.GetSqlStringCommond(sql);
                var table = cn.ExecuteDataTable(comm);

                for (int i = 0; i < table.Rows.Count; i++)
                {
                    dic.Add(table.Rows[i][0] +Config.Excision + tableName, table.Rows[i][1].ToString());
                }
            }
            catch
            {

            }
        }


        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="tableName"></param>
        private static void CreateTable(string tableName)
        {
            //开启事务
            using (DBTrans ts = new Db.DBTrans(Config.DbConnectionString, Config.DbProviderName))
            {
                DbHelper helper = new DbHelper(ts);
                try
                {
                    const string sqlConst = "(LangId  text not null,LangTxt text,primary key (LangId));";
                    string sqlCreate = " create table " + tableName + " " + sqlConst;
                    helper.ExecuteNonQuery(helper.GetSqlStringCommond(sqlCreate));
                    helper.Commit();
                }
                catch
                {
                    helper.Rollback();
                    throw;
                }

            }

        }


        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private static bool CreateTableExist(string tableName)
        {
            var cn = new Db.DbHelper(Config.DbConnectionString, Config.DbProviderName);
            const string mssql = "select count(1) from sysobjects  where name='{0}' ";
            const string sqlite = "select count(1) from sqlite_master where name='{0}'";

            string sql = "";
            switch (Config.DbProviderName)
            {
                case "System.Data.SQLite": sql = sqlite; break;
                case "System.Data.SqlClient": sql = mssql; break;
                default: new Exception("该数据库类型还没有对应的方法"); break;
            }

            sql = string.Format(sql, tableName);

            int count = Convert.ToInt32(cn.ExecuteScalar(cn.GetSqlStringCommond(sql)));

            return count != 0;
        }
       
        #endregion

    }
}
